可以動態地為物件附加額外的職責。使用裝飾器來擴展功能比使用繼承更有彈性
Head First Design Patterns, 2nd (p.91)
// DecoratorPattern.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
class IiceCream
{
public:
virtual void Make() = 0;
virtual ~IiceCream() { }
};
class SimpleIceCream: public IiceCream
{
public:
virtual void Make()
{
std::cout<<"\n milk + sugar + Ice cream Powder";
}
};
class IceCreamDecorator: public IiceCream
{
public:
IceCreamDecorator(IiceCream& decorator):m_Decorator(decorator)
{
}
virtual void Make()
{
m_Decorator.Make();
}
private:
IiceCream& m_Decorator;
};
class WithFruits : public IceCreamDecorator
{
public:
WithFruits(IiceCream& decorator):IceCreamDecorator(decorator)
{
}
virtual void Make()
{
IceCreamDecorator::Make();
std::cout<<" + Fruits";
}
};
class WithNuts : public IceCreamDecorator
{
public:
WithNuts(IiceCream& decorator):IceCreamDecorator(decorator)
{
}
virtual void Make()
{
IceCreamDecorator::Make();
std::cout<<" + Nuts";
}
};
class WithWafers : public IceCreamDecorator
{
public:
WithWafers(IiceCream& decorator):IceCreamDecorator(decorator)
{
}
virtual void Make()
{
IceCreamDecorator::Make();
std::cout<<" + Wafers";
}
};
int _tmain(int argc, _TCHAR* argv[])
{
IiceCream* pIceCreamSimple = new SimpleIceCream();
pIceCreamSimple->Make();
IiceCream* pIceCreamFruits = new WithFruits(*pIceCreamSimple);
pIceCreamFruits->Make();
IiceCream* pIceCreamNuts = new WithNuts(*pIceCreamFruits);
pIceCreamNuts->Make();
IiceCream* pIceCreamWafers = new WithWafers(*pIceCreamNuts);
pIceCreamWafers->Make();
delete pIceCreamSimple;
delete pIceCreamFruits;
delete pIceCreamNuts;
delete pIceCreamWafers;
return 0;
}
[1]. https://refactoring.guru/design-patterns/decorator/cpp/example
[2]. https://cppcodetips.wordpress.com/2016/10/31/decorator-pattern-explained-with-c-sample/
[3]. https://www.bogotobogo.com/DesignPatterns/decorator.php